# -*- coding: utf-8 -*-
# @Date   : 2021/03/31
# @File   : CF08_Mon24ARQuarterGradient.py
# @Author : zhanghengfeng

'''eof
name:近24个月货物贸易回款值季均变化率
code:CF08_Mon24ARQuarterGradient
tableName:
columnName:
groups:出口信息模块
dependencies:CF_CQ_DSJ
type:常用指标
dataSourceType:
eof'''
from __future__ import division 
import pandas as pd
import numpy as np
import datetime

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def goodslist_method(data,length):
    '''
    Explanation
    --------------
    获取近期指定月份数长度升序排列的出口货物金额列表
    
    Parameters
    ------------
    data: json
        数据接口直接获取到的数据
    
    length: int
        时间月份数长度
        
    Return
    ------
    amount_list: list
        金额列表
    '''
    
    #获取receipt表失败时，返回缺失值
    try:
        receipt = data['body']['baseInfo'][0]['receipt']
        if receipt in null_type_list or receipt == []:
            return u'缺失值'
        elif isinstance(receipt,list) and len(receipt)>0:
            
            #生成字符串形式的升序时间列表
            last_month_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset\
                                (months=i)).strftime('%Y%m%d')[:6] for i in range(1, 1+length)]
            
            #根据上述列表生成对应月份为0元的记录的字典
            last_month_dict = {}
            for i in last_month_list:
                last_month_dict[i] = 0
            
            #遍历所有的申报记录，对相应月份进行字段值更新
            errorConts = 0
            for i in receipt:
                try:
                    #月份
                    month = i.get('month')
                    #金额
                    goods = i.get('goods')
                    if isfloat(month) and isfloat(goods) and isinstance(int(month),int) and len(month) == 6:
                        if i['month'] in last_month_list and float(goods) > 0:
                            last_month_dict.update({i['month']:float(i['goods'])})
                        else:
                            pass
                    else:
                        errorConts += 1
                except:
                    errorConts += 1
            if errorConts == len(receipt):
                return u'缺失值'
            else:
                #按年份对字典进行降序排列，现在目测数据条目是时间顺序排列的，所以还是先排个序稳当点
                last_month_dict_f = {}
                for i in sorted (last_month_dict):
                    last_month_dict_f[i] = last_month_dict[i]
                                
                #返回列表形式的字典字段值,使用last_month_dict_f.values()会打乱顺序
                amount_list = list(pd.DataFrame([last_month_dict_f]).iloc[0,:])
                return amount_list
        else:
            return u'缺失值'
    except:
        return u'缺失值'
    
def CF08_Mon24ARQuarterGradient():
    try:
        list_result = goodslist_method(CF_CQ_DSJ,24)
        if list_result == u'缺失值':
            return u'缺失值'
    except:
        return u'缺失值'
    cal_amount = []
    for i in range(8):
        cal_amount.append(sum(list_result[i*3:(i+1)*3]))
    cal_amount=list(reversed(cal_amount))
    cal_ratio = []
    for i in range(len(cal_amount)-1):
        if cal_amount[i+1] == 0:
            cal_ratio.append(0)
        else:
            cal_ratio.append(round((cal_amount[i] - cal_amount[i+1])/cal_amount[i+1],4))
    return round(np.mean(cal_ratio),4)

result = CF08_Mon24ARQuarterGradient()